from datetime import datetime

from sanic.views import HTTPMethodView

from apps.baseview import BaseAsyncRetrieveUpdateDestroyApi
from apps.model import UserDocument
from apps.schemas import user_schema


class UserAsyncListCreateApi(HTTPMethodView):
    async def get(self, request):
        data = [user_schema.dump(item).data for item in UserDocument.objects]
        return {"msg": "ok", "data": data}

    async def post(self, request):
        data = request.json
        query = UserDocument(
            username=data.get('username'),
            password=data.get("password"),
            email=data.get('email')).save()
        dump_data = user_schema.dump(query).data
        return {"msg": "ok", "data": dump_data}


class UserAsyncRetrieveUpdateDestroyApi(BaseAsyncRetrieveUpdateDestroyApi):
    async def get(self, request, pk):
        doc = UserDocument.objects(id=pk).first()
        if doc is not None:
            return {"msg": "ok", "data": user_schema.dump(doc).data}
        return {"msg": "ok", "data": None}

    async def update(self, request, pk):
        UserDocument.objects(id=pk).update(**request.json)
        return {"msg": "ok"}

    async def delete(self, request, pk):
        UserDocument.objects(id=pk).update(**{
            'is_del': True,
            'update_at': datetime.now()
        })
        return {"msg": "ok"}
